
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuConfig;
import com.hlkj.pay.app.merchant.ext.impl.huifu.utils.HuiFuUtil;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.dto.merchant.ProviderChannelFeeConfigList;
import com.hlkj.pay.dto.provider.DefaultFeeConfig;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessBusinessDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessCardDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessCertInfoDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.MerchantUtils;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBusiModifyRequest;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBusiOpenRequest;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
public class HuiFuMerchantOpenRequestParamsHandle {

    /**
     * 企业商户业务开通
     *
     * @param channelMerchantBusinessContext
     * @return
     */
    public static CommonResult<V2MerchantBusiOpenRequest> v2MerchantBusiOpenRequest(ChannelMerchantAccessContext channelMerchantBusinessContext) {
        // https://paas.huifu.com/partners/api/#/shgl/shywkt/api_shjj_shywkt_kyc
        // 2.组装请求参数
        V2MerchantBusiOpenRequest request = new V2MerchantBusiOpenRequest();
        // 请求流水号
        request.setReqSeqId(SequenceTools.getReqSeqId32());
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        // 设置非必填字段
        CommonResult<Map<String, Object>> extendInfoMap = getExtendInfos(channelMerchantBusinessContext);
        if (!extendInfoMap.isSuccess()) {
            return CommonResult.error(extendInfoMap.getCode(), extendInfoMap.getMsg());
        }
        request.setExtendInfo(extendInfoMap.getData());
        return CommonResult.success(request);
    }
    /**
     * 企业商户业务开通
     *
     * @param channelMerchantBusinessContext
     * @return
     */
    public static CommonResult<V2MerchantBusiModifyRequest> v2MerchantBusiModifyRequest(ChannelMerchantAccessContext channelMerchantBusinessContext) {
        // https://paas.huifu.com/partners/api/#/shgl/shywkt/api_shjj_shywkt_kyc
        // 2.组装请求参数
        V2MerchantBusiModifyRequest request = new V2MerchantBusiModifyRequest();
        // 请求流水号
        request.setReqSeqId(SequenceTools.getReqSeqId32());
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        // 设置非必填字段
        CommonResult<Map<String, Object>> extendInfoMap = getUpdateExtendInfos(channelMerchantBusinessContext);
        if (!extendInfoMap.isSuccess()) {
            return CommonResult.error(extendInfoMap.getCode(), extendInfoMap.getMsg());
        }
        request.setExtendInfo(extendInfoMap.getData());
        return CommonResult.success(request);
    }


    /**
     * 非必填字段
     * 
     * @return
     */
    private static CommonResult<Map<String, Object>> getExtendInfos(ChannelMerchantAccessContext channelMerchantBusinessContext) {
        MerchantAccessDto merchantAccessDto = channelMerchantBusinessContext.getMerchantAccessDto();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();

        // 经营简称
        extendInfoMap.put("short_name", merchantAccessBusiness.getShortName());
        // extendInfoMap.put("upper_huifu_id", merchantAccessInfo.getSubMchId());
        // 签约人
        extendInfoMap.put("sign_user_info", getSignUserInfo(merchantAccessDto.getMerchantAccessCard(),merchantAccessDto.getMerchantAccessContact(), merchantAccessDto.getMerchantAccessLegal()));
        // online_flag quick_flag withhold_flag mer_bus_type out_fee_flag
        // out_fee_huifuid 暂不配置
        ProviderChannelConfigDO providerChannelConfigDO = channelMerchantBusinessContext.getProviderChannelConfig();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        HuiFuConfig huiFuConfig = JsonUtils.parseObject(channelConfig, HuiFuConfig.class);

        MerchantAccessBusinessDO merchantAccessScene = merchantAccessDto.getMerchantAccessBusiness();
        List<ProviderChannelFeeConfigList> merchantFeeConfigList = channelMerchantBusinessContext.getMerchantFeeConfigList();
        Map<Integer, List<ProviderChannelFeeConfigList>> merchantFeeConfigMap = merchantFeeConfigList.stream()
                .collect(Collectors.groupingBy(merchantFeeConfig -> merchantFeeConfig.getPayWayDO().getType()));

        for (Map.Entry<Integer, List<ProviderChannelFeeConfigList>> entry : merchantFeeConfigMap.entrySet()) {
            List<ProviderChannelFeeConfigList> values = entry.getValue();
            PayWayDO payWayDO = values.get(0).getPayWayDO();
            switch (PayEnums.PAY_TYPE.fromByCode(payWayDO.getType())) {
                case WECHAT:
                    // 微信配置对象
                    extendInfoMap.put("wx_conf_list", getWechatConfList(merchantAccessDto,huiFuConfig, values, extendInfoMap));
                    break;
                case ALIPAY:
                    List<ProviderChannelFeeConfigList> aliScanList=values.stream().filter(value-> PayEnums.SCENE_PAY_TYPE.QR.getType().equals(value.getPayWayDO().getSubType())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(aliScanList)){
                        if(aliScanList.size()>1){
                            List<ProviderChannelFeeConfigList> collect = aliScanList.stream().filter(value -> PayEnums.SCENE_TYPE.OFFLINE.getCode().equals(value.getPayWayDO().getSceneType())).collect(Collectors.toList());
                            extendInfoMap.put("ali_conf_list", getAliConfList(merchantAccessDto,huiFuConfig, collect,extendInfoMap));
                        }else {
                            // 支付宝配置对象
                            extendInfoMap.put("ali_conf_list", getAliConfList(merchantAccessDto,huiFuConfig, aliScanList, extendInfoMap));
                        }
                    }
                    break;

                default:
            }
        }
        // 协议信息实体
        extendInfoMap.put("agreement_info", getAgreementInfo());
        extendInfoMap.put("async_return_url", channelMerchantBusinessContext.getAsyncReturnUrl());
        extendInfoMap.put("busi_async_return_url", channelMerchantBusinessContext.getAsyncReturnUrl());
        // extendInfoMap.put("recon_resp_addr", channelMerchantBusinessContext.getAsyncTransUrl());
        return CommonResult.success(extendInfoMap);
    }
    /**
     * 非必填字段
     *
     * @return
     */
    private static CommonResult<Map<String, Object>> getUpdateExtendInfos(ChannelMerchantAccessContext channelMerchantBusinessContext) {
        MerchantAccessDto merchantAccessDto = channelMerchantBusinessContext.getMerchantAccessDto();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();

        // 经营简称
        extendInfoMap.put("short_name", merchantAccessBusiness.getShortName());
        // extendInfoMap.put("upper_huifu_id", merchantAccessInfo.getSubMchId());
        // 签约人
        extendInfoMap.put("sign_user_info", getSignUserInfo(merchantAccessDto.getMerchantAccessCard(),merchantAccessDto.getMerchantAccessContact(), merchantAccessDto.getMerchantAccessLegal()));
        // online_flag quick_flag withhold_flag mer_bus_type out_fee_flag
        // out_fee_huifuid 暂不配置
        ProviderChannelConfigDO providerChannelConfigDO = channelMerchantBusinessContext.getProviderChannelConfig();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        HuiFuConfig huiFuConfig = JsonUtils.parseObject(channelConfig, HuiFuConfig.class);

        MerchantAccessBusinessDO merchantAccessScene = merchantAccessDto.getMerchantAccessBusiness();
        List<ProviderChannelFeeConfigList> merchantFeeConfigList = channelMerchantBusinessContext.getMerchantFeeConfigList();
        Map<Integer, List<ProviderChannelFeeConfigList>> merchantFeeConfigMap = merchantFeeConfigList.stream()
                .collect(Collectors.groupingBy(merchantFeeConfig -> merchantFeeConfig.getPayWayDO().getType()));

        for (Map.Entry<Integer, List<ProviderChannelFeeConfigList>> entry : merchantFeeConfigMap.entrySet()) {
            List<ProviderChannelFeeConfigList> values = entry.getValue();
            PayWayDO payWayDO = values.get(0).getPayWayDO();
            switch (PayEnums.PAY_TYPE.fromByCode(payWayDO.getType())) {
                case WECHAT:
                    // 微信配置对象
                    extendInfoMap.put("wx_conf_list", getUpdateWechatConfList(merchantAccessDto,huiFuConfig, values, extendInfoMap));
                    break;
                case ALIPAY:
                    List<ProviderChannelFeeConfigList> aliScanList=values.stream().filter(value-> PayEnums.SCENE_PAY_TYPE.QR.getType().equals(value.getPayWayDO().getSubType())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(aliScanList)){
                        if(aliScanList.size()>1){
                            List<ProviderChannelFeeConfigList> collect = aliScanList.stream().filter(value -> PayEnums.SCENE_TYPE.OFFLINE.getCode().equals(value.getPayWayDO().getSceneType())).collect(Collectors.toList());
                            extendInfoMap.put("ali_conf_list", getUpdateAliConfList(merchantAccessDto,huiFuConfig, collect,extendInfoMap));
                        }else {
                            // 支付宝配置对象
                            extendInfoMap.put("ali_conf_list", getUpdateAliConfList(merchantAccessDto,huiFuConfig, aliScanList, extendInfoMap));
                        }
                    }
                    break;

                default:
            }
        }
        // 协议信息实体
        extendInfoMap.put("agreement_info", getAgreementInfo());
        extendInfoMap.put("async_return_url", channelMerchantBusinessContext.getAsyncReturnUrl());
        extendInfoMap.put("busi_async_return_url", channelMerchantBusinessContext.getAsyncReturnUrl());
        // extendInfoMap.put("recon_resp_addr", channelMerchantBusinessContext.getAsyncTransUrl());
        return CommonResult.success(extendInfoMap);
    }

    public static String getSignUserInfo(MerchantAccessCardDO merchantAccessCard,MerchantAccessCertInfoDO merchantAccessCertDO, MerchantAccessCertInfoDO merchantAccessLegal) {
        JSONObject dto = new JSONObject();
        // 签约人类型
        // LEGAL-法人，对公结算或对私法人结算时可选法人签约；
        // CONTACT-联系人，对公结算可选联系人（经办人）签约；
        // OTHER-其他，对私非法人结算选“其他”，必须是结算人；
        switch (MerchantEnum.CARD_TYPE.from(merchantAccessCard.getType())){
            case PRIVATE_NON_CORPORATE_ACCOUNT:
                dto.put("type", "OTHER");
                // 手机号
                dto.put("mobile_no", merchantAccessCard.getCardPhone());
                dto.put("name", merchantAccessCard.getName());
                dto.put("cert_no", merchantAccessCard.getCertNo());
                break;
            default:
                dto.put("type", "LEGAL");
                // 手机号
                dto.put("mobile_no", merchantAccessLegal.getPhone());
                dto.put("name", merchantAccessLegal.getName());
                dto.put("cert_no", merchantAccessLegal.getCertNo());
        }
        // name cert_no 非 法人类型可不传
        return dto.toJSONString();
    }

    private static String getSplitConfInfo() {
        JSONObject dto = new JSONObject();
        // 分账规则来源
        // L01 接口发起 02页面配置
        dto.put("rule_origin", "01");
        // 分账开关
        dto.put("div_flag", "Y");
        // 最大分账比例%
        dto.put("apply_ratio", "20.00");
        // 生效类型
        dto.put("start_type", "0");
        // 手续费
        dto.put("split_fee_rate", "0");
        // 固定手续费
        dto.put("per_amt", "0");
        // 分账模式
        dto.put("scene", "00");
        // name cert_no 非 法人类型可不传
        return dto.toJSONString();
    }

    public static String getAgreementInfo() {
        JSONObject dto = new JSONObject();
        // 协议类型
        // 0-电子协议 1-纸质协议 3-挂网协议；
        dto.put("agreement_type", "0");
        return dto.toJSONString();
    }



    private static String getAliConfList(MerchantAccessDto merchantAccessDto,HuiFuConfig huiFuConfig, List<ProviderChannelFeeConfigList> providerChannelFeeConfigs,Map<String, Object> extendInfoMap) {
        MerchantAccessBusinessDO merchantAccessScene = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessInfoDO merchantAccessInfoDO = merchantAccessDto.getMerchantAccessInfo();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        JSONArray dtoList = new JSONArray();
        PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(merchantAccessScene.getSceneType());

        Map<String, ProviderChannelFeeConfigList> feeConfigMap = providerChannelFeeConfigs.stream()
                .collect(Collectors.toMap(providerChannelFeeConfig -> providerChannelFeeConfig.getPayWayCode(), Function.identity(), (t1, t2) -> t1));
        providerChannelFeeConfigs.stream().forEach(channelFeeConfigList -> {
            ProviderChannelFeeConfigList providerChannelFeeConfig = feeConfigMap.get(channelFeeConfigList.getPayWayDO().getCode());
            PayWayDO payWayDO = providerChannelFeeConfig.getPayWayDO();
            DefaultFeeConfig defaultFeeConfigValue = providerChannelFeeConfig.getDefaultFeeConfigValue();
            JSONObject dto = new JSONObject();
            // 支付场景 1.线下扫码，2.线上扫码，3.非盈利费率（需活动报名）；示例值：1 如果一次请求配置了多个场景，以第一个类型为默认场景；
            dto.put("pay_scene", "1");
            // 手续费（%）
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // fee_min_amt
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString(MerchantUtils.divide(defaultFeeConfigValue.getRateBase(), new BigDecimal(100))));
            dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // 商户经营类目
            dto.put("mcc", merchantAccessScene.getAlipayMcc());
            // 子渠道号
            dto.put("pay_channel_id", huiFuConfig.getAlipayChannelId());
            // 拟申请的间联商户等级
            // dto.put("indirect_level", "");
            // 功能开关
            // dto.put("switch_state", "Y");
            // 是否需要实名认证
            dto.put("is_check_real_name", "Y");
            // JSONObject eal_name = new JSONObject();
            Map<String,String> params=new HashMap<>();
            // 是否金融机构
            params.put("finance_institution_flag", "false");
            if(MerchantEnum.MERCHANT_TYPE.COMPANY.getCode().equals(merchantAccessInfoDO.getType())) {
                // 证书类型
                params.put("cert_type", "CERTIFICATE_TYPE_2389");
            }else {
                // 小微经营类型
                params.put("micro_biz_type", "MICRO_TYPE_STORE");
            }
            // 实名认证信息
            dto.put("al_real_name_info", params);
            dtoList.add(dto);

        });

        return dtoList.toJSONString();
    }
    private static String getUpdateAliConfList(MerchantAccessDto merchantAccessDto,HuiFuConfig huiFuConfig, List<ProviderChannelFeeConfigList> providerChannelFeeConfigs,Map<String, Object> extendInfoMap) {
        MerchantAccessBusinessDO merchantAccessScene = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessInfoDO merchantAccessInfoDO = merchantAccessDto.getMerchantAccessInfo();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        JSONArray dtoList = new JSONArray();
        PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(merchantAccessScene.getSceneType());

        Map<String, ProviderChannelFeeConfigList> feeConfigMap = providerChannelFeeConfigs.stream()
                .collect(Collectors.toMap(providerChannelFeeConfig -> providerChannelFeeConfig.getPayWayCode(), Function.identity(), (t1, t2) -> t1));
        providerChannelFeeConfigs.stream().forEach(channelFeeConfigList -> {
            ProviderChannelFeeConfigList providerChannelFeeConfig = feeConfigMap.get(channelFeeConfigList.getPayWayDO().getCode());
            PayWayDO payWayDO = providerChannelFeeConfig.getPayWayDO();
            DefaultFeeConfig defaultFeeConfigValue = providerChannelFeeConfig.getDefaultFeeConfigValue();
            JSONObject dto = new JSONObject();
            // 支付场景 1.线下扫码，2.线上扫码，3.非盈利费率（需活动报名）；示例值：1 如果一次请求配置了多个场景，以第一个类型为默认场景；
            dto.put("pay_scene", "1");
            // 手续费（%）
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // fee_min_amt
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString(MerchantUtils.divide(defaultFeeConfigValue.getRateBase(), new BigDecimal(100))));
            dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // 商户经营类目
            dto.put("mcc", merchantAccessScene.getAlipayMcc());
            // 子渠道号
            dto.put("pay_channel_id", huiFuConfig.getAlipayChannelId());
            // 拟申请的间联商户等级
            // dto.put("indirect_level", "");
            // 功能开关
            dto.put("switch_state", "1");
            // 是否需要实名认证
            dto.put("is_check_real_name", "Y");
            // JSONObject eal_name = new JSONObject();
            Map<String,String> params=new HashMap<>();
            // 是否金融机构
            params.put("finance_institution_flag", "false");
            if(MerchantEnum.MERCHANT_TYPE.COMPANY.getCode().equals(merchantAccessInfoDO.getType())) {
                // 证书类型
                params.put("cert_type", "CERTIFICATE_TYPE_2389");
            }else {
                // 小微经营类型
                params.put("micro_biz_type", "MICRO_TYPE_STORE");
            }
            // 实名认证信息
            dto.put("al_real_name_info", params);
            dtoList.add(dto);

        });

        return dtoList.toJSONString();
    }

    private static String getWechatConfList(MerchantAccessDto merchantAccessDto,HuiFuConfig huiFuConfig, List<ProviderChannelFeeConfigList> providerChannelFeeConfigs,Map<String, Object> extendInfoMap) {
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        JSONArray dtoList = new JSONArray();
        Map<String, ProviderChannelFeeConfigList> feeConfigMap = providerChannelFeeConfigs.stream()
                .collect(Collectors.toMap(providerChannelFeeConfigDomain -> providerChannelFeeConfigDomain.getPayWayCode(), Function.identity(), (t1, t2) -> t1));
        providerChannelFeeConfigs.stream().forEach(commonAppDO -> {
            ProviderChannelFeeConfigList providerChannelFeeConfigDomain = feeConfigMap.get(commonAppDO.getPayWayDO().getCode());
            PayWayDO payWayDO = providerChannelFeeConfigDomain.getPayWayDO();
            DefaultFeeConfig defaultFeeConfigValue = providerChannelFeeConfigDomain.getDefaultFeeConfigValue();
            JSONObject dto = new JSONObject();
            PayEnums.SCENE_PAY_TYPE scenePayType = PayEnums.SCENE_PAY_TYPE.fromByType(payWayDO.getSubType());

            PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(payWayDO.getSceneType());
            Integer payScene = null;
            switch (sceneType) {
                case ONLINE:
                    switch (scenePayType) {
                        case MINI_APP:
                            payScene = 5;
                            break;
                        case JSAPI:
                            payScene = 4;
                            break;
                        case SCAN:
                            payScene = 12;
                            break;
                        case APP:
                            payScene = 13;
                            return;
                        default:
                            return;
                    }
                    break;
                case OFFLINE:
                    switch (scenePayType) {
                        case MINI_APP:
                            payScene = 3;
                            break;
                        case JSAPI:
                            payScene = 2;
                            break;
                        case SCAN:
                            payScene = 1;
                            break;
                        default:
                            return;
                    }
                    break;
            }
            // 支付场景
            dto.put("pay_scene", payScene);
            // 手续费（%）
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString(MerchantUtils.divide(defaultFeeConfigValue.getRateBase(), new BigDecimal(100))));
            dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // fee_min_amt
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // 商户经营类目
            dto.put("mcc", merchantAccessBusiness.getMcc());
            // 子渠道号
            dto.put("pay_channel_id", huiFuConfig.getWechatChannelId());
            // 拟申请的间联商户等级
            // dto.put("indirect_level", "");
            // 功能开关
            // dto.put("switch_state", "Y");
            // 是否需要实名认证
            dto.put("is_check_real_name", "Y");
            // JSONObject eal_name = new JSONObject();
            Map<String,String> params=new HashMap<>();
            // 是否金融机构
            params.put("finance_institution_flag", "false");
            if(MerchantEnum.MERCHANT_TYPE.COMPANY.getCode().equals(merchantAccessInfo.getType())){
                // 证书类型
                params.put("cert_type", "CERTIFICATE_TYPE_2389");
                // 实名认证信息
                if(!merchantAccessLegal.getCertNo().equals(merchantAccessContact.getCertNo())){
                    params.put("contact_type", "SUPER");
                    CommonResult<String> f28 = HuiFuUtil.fileUpload(merchantAccessContact.getCertBackUrl(), "联系人身份证正面照","F28");
                    CommonResult<String> f29 = HuiFuUtil.fileUpload(merchantAccessContact.getCertFrontUrl(), "联系人身份证反面照","F29");
                    List<Map<String, Object>> map = new ArrayList<>();
                    Map<String, Object> f28Map = new HashMap<>();
                    f28Map.put("file_type", "F28");
                    f28Map.put("file_id", f28.getData());
                    Map<String, Object> f29Map = new HashMap<>();
                    f29Map.put("file_type", "F29");
                    f29Map.put("file_id", f29.getData());
                    map.add(f28Map);
                    map.add(f29Map);
                    // 文件列表
                    extendInfoMap.put("extended_material_list", JsonUtils.toJsonString(map));
                    params.put("name", merchantAccessContact.getName());
                    params.put("mobile", merchantAccessContact.getPhone());
                    params.put("contact_id_doc_type", HuiFuMerchantAccessCommonParamsHandle.certType(merchantAccessContact.getCertType()));
                    params.put("id_card_number", merchantAccessContact.getCertNo());
                    params.put("contact_period_begin", merchantAccessContact.getCertBeginDate());
                    params.put("contact_period_end", merchantAccessContact.getCertEndDate());
                }else {
                    params.put("contact_type", "LEGAL");
                }
            }else {
                // 小微经营类型
                params.put("micro_biz_type", "MICRO_TYPE_STORE");
                params.put("contact_type", "LEGAL");
            }
            dto.put("wx_real_name_info", params);
            dtoList.add(dto);

        });

        return dtoList.toJSONString();
    }
    private static String getUpdateWechatConfList(MerchantAccessDto merchantAccessDto,HuiFuConfig huiFuConfig, List<ProviderChannelFeeConfigList> providerChannelFeeConfigs,Map<String, Object> extendInfoMap) {
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        JSONArray dtoList = new JSONArray();
        Map<String, ProviderChannelFeeConfigList> feeConfigMap = providerChannelFeeConfigs.stream()
                .collect(Collectors.toMap(providerChannelFeeConfigDomain -> providerChannelFeeConfigDomain.getPayWayCode(), Function.identity(), (t1, t2) -> t1));
        providerChannelFeeConfigs.stream().forEach(commonAppDO -> {
            ProviderChannelFeeConfigList providerChannelFeeConfigDomain = feeConfigMap.get(commonAppDO.getPayWayDO().getCode());
            PayWayDO payWayDO = providerChannelFeeConfigDomain.getPayWayDO();
            DefaultFeeConfig defaultFeeConfigValue = providerChannelFeeConfigDomain.getDefaultFeeConfigValue();
            JSONObject dto = new JSONObject();
            PayEnums.SCENE_PAY_TYPE scenePayType = PayEnums.SCENE_PAY_TYPE.fromByType(payWayDO.getSubType());

            PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(payWayDO.getSceneType());
            Integer payScene = null;
            switch (sceneType) {
                case ONLINE:
                    switch (scenePayType) {
                        case MINI_APP:
                            payScene = 5;
                            break;
                        case JSAPI:
                            payScene = 4;
                            break;
                        case SCAN:
                            payScene = 12;
                            break;
                        case APP:
                            payScene = 13;
                            return;
                        default:
                            return;
                    }
                    break;
                case OFFLINE:
                    switch (scenePayType) {
                        case MINI_APP:
                            payScene = 3;
                            break;
                        case JSAPI:
                            payScene = 2;
                            break;
                        case SCAN:
                            payScene = 1;
                            break;
                        default:
                            return;
                    }
                    break;
            }
            // 支付场景
            dto.put("pay_scene", payScene);
            // 手续费（%）
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString(MerchantUtils.divide(defaultFeeConfigValue.getRateBase(), new BigDecimal(100))));
            dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // fee_min_amt
            // dto.put("fee_rate", MerchantUtils.bigDecimalToString2(defaultFeeConfigValue.getRateBase()));
            // 商户经营类目
            dto.put("mcc", merchantAccessBusiness.getMcc());
            // 子渠道号
            dto.put("pay_channel_id", huiFuConfig.getWechatChannelId());
            // 拟申请的间联商户等级
            // dto.put("indirect_level", "");
            // 功能开关
            // 功能开关
            dto.put("switch_state", "1");
            // 是否需要实名认证
            dto.put("is_check_real_name", "Y");
            // JSONObject eal_name = new JSONObject();
            Map<String,String> params=new HashMap<>();
            // 是否金融机构
            params.put("finance_institution_flag", "false");
            if(MerchantEnum.MERCHANT_TYPE.COMPANY.getCode().equals(merchantAccessInfo.getType())){
                // 证书类型
                params.put("cert_type", "CERTIFICATE_TYPE_2389");
                // 实名认证信息
                if(!merchantAccessLegal.getCertNo().equals(merchantAccessContact.getCertNo())){
                    params.put("contact_type", "SUPER");
                    CommonResult<String> f28 = HuiFuUtil.fileUpload(merchantAccessContact.getCertBackUrl(), "联系人身份证正面照","F28");
                    CommonResult<String> f29 = HuiFuUtil.fileUpload(merchantAccessContact.getCertFrontUrl(), "联系人身份证反面照","F29");
                    List<Map<String, Object>> map = new ArrayList<>();
                    Map<String, Object> f28Map = new HashMap<>();
                    f28Map.put("file_type", "F28");
                    f28Map.put("file_id", f28.getData());
                    Map<String, Object> f29Map = new HashMap<>();
                    f29Map.put("file_type", "F29");
                    f29Map.put("file_id", f29.getData());
                    map.add(f28Map);
                    map.add(f29Map);
                    // 文件列表
                    extendInfoMap.put("extended_material_list", JsonUtils.toJsonString(map));
                    params.put("name", merchantAccessContact.getName());
                    params.put("mobile", merchantAccessContact.getPhone());
                    params.put("contact_id_doc_type", HuiFuMerchantAccessCommonParamsHandle.certType(merchantAccessContact.getCertType()));
                    params.put("id_card_number", merchantAccessContact.getCertNo());
                    params.put("contact_period_begin", merchantAccessContact.getCertBeginDate());
                    params.put("contact_period_end", merchantAccessContact.getCertEndDate());
                }else {
                    params.put("contact_type", "LEGAL");
                }
            }else {
                // 小微经营类型
                params.put("micro_biz_type", "MICRO_TYPE_STORE");
                params.put("contact_type", "LEGAL");
            }
            dto.put("wx_real_name_info", params);
            dtoList.add(dto);

        });

        return dtoList.toJSONString();
    }

}
